<?php

namespace app\storecheck\logic;

use think\facade\Db;
use think\facade\Cache;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;
use app\common\library\Excel;

class WarehouseEntryLogic extends BasicLogic
{

    public function __construct()
    {
        
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $create_time     = $params['create_time'] ?? '';
        $delivery_time     = $params['delivery_time'] ?? '';
        $spu     = $params['spu'] ?? '';

        $limit = $params['limit'] ?? 10;
        $where = [];

        if($create_time){
            $where[]  = ['create_time', '>=',$create_time[0]];
            $where[]  = ['create_time', '<=',$create_time[1]];
        }
        if($delivery_time){
            $where[]  = ['delivery_time', '>=',$delivery_time[0]];
            $where[]  = ['delivery_time', '<=',$delivery_time[1]];
        }
        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }
        
        $list = Db::name('feishu_warehouse_entry')
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);

        $lists = $list->items();

        $data = [
            'list'  => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    public function add($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $result = false;
        Db::startTrans();
        try {
            //广告账户
            // $result = Db::name('advaccount')->insert($AdvertisingAccount);
            if ($result !== false) { 
                Db::commit();
                return json(DefaultResponse(200, true, '添加成功!', null));
            }
            Db::rollback();
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, '广告账户已存在!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));

    }

    public function find($id)
    {
        $where['id'] = $id;
        $row = Db::name('conversations')
            ->where($where)
            ->find();
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        return json(DefaultResponse(200, true, '获取成功', $row));
    }

    public function edit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $id = $data['id'];
        // $row = $this->model->find($id);
        // if (empty($row)) {
        //     return json(DefaultResponse(201, false, '数据不存在!', null));
        // }
        $result = false;
        Db::startTrans();
        try {
            // $result = $row->save($AdvertisingAccount);
            if ($result) {
                Db::commit();
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            Db::rollback();
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        Db::rollback();
        return json(DefaultResponse(200, false, '更新成功!', null));
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['时间', '时间'];
        $header[] = ['颜色', '颜色'];
        $header[] = ['C', 'C'];
        $header[] = ['D', 'D'];
        $header[] = ['E', 'E'];
        $header[] = ['F', 'F'];
        $header[] = ['总计', '总计'];
        $tableName = "WarehouseEntry";
        
        
        $lists = [
            [
                '时间' => '2025/6/7',
                '颜色' => 'beige',
                'C' => 1,
                'D' => 2,
                'E' => 3,
                'F' => 4,
                '总计' => 10,
            ],
            [
                '时间' => '2025/6/7',
                '颜色' => 'caramel',
                'C' => 1,
                'D' => 2,
                'E' => 3,
                'F' => 4,
                '总计' => 10,
            ],
            [
                '时间' => '总计',
                '颜色' => '',
                'C' => 2,
                'D' => 4,
                'E' => 6,
                'F' => 8,
                '总计' => 20,
            ],
            [
                '时间' => 'SPU',
                '颜色' => 'swim116',
                'C' => "",
                'D' => "",
                'E' => "",
                'F' => "",
                '总计' => "",
            ],
        ];
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    
    

    /**
     * @desc   import
     * @author zhagnheng
     * @date   2024-07-27
     */
    public function importInfo($url){
        $data             = Excel::getExcelData('.' . '/' . $url);
        
        $excelDatas        = isset($data[0]) ? $data[0] : $data;
        if(!$excelDatas)    return json(DefaultResponse(201, false, '暂无数据!', null));
        // halt($excelDatas);
        
        $inserts = [];
        foreach($excelDatas as $row){
            if (isset($row['A']) && $row['A'] === "SPU") {
                $spu = $row['B'];
                continue;
            }
            if  (!isset($row['A']) || !$row['A']) {
                continue;
            }
            $create_time = strtotime($row['A']);
            if(empty($create_time)){
                continue;
            }
            //数量
            $count = count($row) - 1;
            $lastKey = array_keys($row);
            $lastKey = $lastKey[$count];
            $num = $row[$lastKey];
            //数量
            
            $insert = [
                'create_time' => date('Y-m-d', $create_time),
                'color' => $row['B'],
                'num' => $num,
            ];
            $inserts[] = $insert;
        }
        if(!isset($spu) && empty($spu)){
            return json(DefaultResponse(201, false, '请填写SPU!', null));
        }
        foreach ($inserts as &$v) {
            $v['spu'] = $spu;
            $warehouse_entry = Db::name('feishu_warehouse_entry')
                ->where('spu',$v['spu'])
                ->where('create_time',$v['create_time'])
                ->where('color',$v['color'])
                ->find();
            if($warehouse_entry){
                Db::name('feishu_warehouse_entry')->where('id',$warehouse_entry['id'])->update($v);
            }else{
                Db::name('feishu_warehouse_entry')->insert($v);
            }
        }
        return json(DefaultResponse(200, false, '导入成功!', null));
    }

    
    
}
